package com.kunda.netty.test;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.google.protobuf.GeneratedMessage;

public class PBMessageConvert extends AbstractHttpMessageConverter<GeneratedMessage>{

	@Override
	protected boolean supports(Class<?> clazz) {
		return GeneratedMessage.class.isAssignableFrom(clazz);
	}

	@Override
	protected GeneratedMessage readInternal(
			Class<? extends GeneratedMessage> clazz,
			HttpInputMessage inputMessage) throws IOException,
			HttpMessageNotReadableException {
		
		try {
			Method method = clazz.getDeclaredMethod("parseFrom", InputStream.class);
			
			GeneratedMessage message = (GeneratedMessage) method.invoke(clazz, inputMessage.getBody());
			return message;
			
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void writeInternal(GeneratedMessage t,
			HttpOutputMessage outputMessage) throws IOException,
			HttpMessageNotWritableException {
		// TODO Auto-generated method stub
		
	}
	

}
